import { envConfig } from "../config/env-config.js";

interface RerankRequest {
  model: string;
  query: string;
  documents: string[];
}

interface RerankResult {
  index: number;
  relevance_score: number;
}

interface RerankResponse {
  results: RerankResult[];
}

export class Reranker {
  private apiKey: string;
  private apiUrl: string;
  private model: string;

  constructor() {
    if (!envConfig.SILICONFLOW_API_KEY) {
      throw new Error("SILICONFLOW_API_KEY is not configured in the environment.");
    }
    this.apiKey = envConfig.SILICONFLOW_API_KEY;
    this.apiUrl = "https://api.siliconflow.cn/v1/rerank";
    this.model = "Qwen/Qwen3-Reranker-8B";
  }

  async rerank(query: string, documents: { originalIndex: number; text: string }[]): Promise<{ originalIndex: number; score: number }[]> {
    if (documents.length === 0) {
      return [];
    }

    const requestBody: RerankRequest = {
      model: this.model,
      query: query,
      documents: documents.map(doc => doc.text),
    };

    try {
      const response = await fetch(this.apiUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      });

      if (!response.ok) {
        const errorBody = await response.text();
        throw new Error(`Reranker API request failed with status ${response.status}: ${errorBody}`);
      }

      const responseData: RerankResponse = await response.json();
      
      // Map the rerank results back to their original indices
      return responseData.results.map(result => ({
        originalIndex: documents[result.index].originalIndex,
        score: result.relevance_score,
      }));

    } catch (error) {
      console.error("Error during reranking:", error);
      // On error, return original indices with a score of 0 to indicate failure
      return documents.map(doc => ({ originalIndex: doc.originalIndex, score: 0 }));
    }
  }
}
